import React, { useState, useEffect } from 'react'
// import Header from "../../components/Header"
import "../char.css"
let websock = null

export default function App(props) {
  let [dataname, setDataname] = useState('')
  let img = sessionStorage.getItem('userimg')
  useEffect(() => {
    const wsuri = "ws://localhost:9990"
    websock = new WebSocket(wsuri);
    initWebSocket(websock);
    return () => websocketclose()
  }, [])

  //发送
  function getdata() {
    if (dataname !== "") {
      let doxs = document.querySelector('.dox')
      const div = document.createElement("li")
      div.innerHTML = `<div class = 'li' className="img"><img src=${img}/></span><p  > ` +
        dataname +
        "</p></div>";
      doxs.appendChild(div)
      websocketsend(JSON.stringify({
        text: dataname,
        img: img,
        name: "111"
      }))
      setDataname('')
      let dox = document.getElementsByClassName('main')[0]
      let lis = document.getElementsByTagName('LI')
      dox.scrollTop = lis[lis.length - 1].offsetTop

    }
  }
  let initWebSocket = () => { //初始化weosocket
    websock.onmessage = websocketonmessage;
    websock.onopen = websocketonopen;
    websock.onerror = websocketonerror;
    websock.onclose = websocketclose;
  }
  function websocketonopen() { //连接建立之后执行send方法发送数据
    if (websock.readyState === 1) {
      console.log('连接成功')
    }
  }
  function websocketonerror() {//连接建立失败重连
    initWebSocket();
  }
  //接收
  function websocketonmessage(msg) { //数据接收
    let { text } = JSON.parse(msg.data)
    let doxs = document.querySelector('.dox')
    const div = document.createElement("li")
    div.innerHTML = `<div class = 'lis' className="img"><img src='https://unsplash.it/400/800/?@name'/><p>` +
      text +
      "</p></div>";
    doxs.appendChild(div)
    let dox = document.getElementsByClassName('main')[0]
    let lis = document.getElementsByTagName('LI')
    dox.scrollTop = lis[lis.length - 1].offsetTop
  }
  let websocketsend = (Data) => {//数据发送
    websock.send(Data)
  }

  function websocketclose(e) {  //关闭
    console.log('断开连接', e);
  }
  return (
    <div className='service'>
      {/* <Header {...props} title={props.location.state.name} /> */}
      <main className='main'>
        <ul className="dox">

        </ul>
      </main>
      <footer>
        <input type="text" placeholder='请输入要说的话' value={dataname} onChange={(e) => {
          setDataname(e.target.value)
        }} onKeyDown={(e) => {
          if (e.keyCode === 13) {
            getdata()
          }
        }} />
        <button onClick={() => {
          getdata()
        }}>发送</button>
      </footer>
    </div>
  )
}
